package handlers

import (
    "context"
    "log"

    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    pb "your_project/proto"
    "your_project/social"
    "your_project/player"
)

// SocialHandler 处理社交相关请求
type SocialHandler struct {
    pb.UnimplementedSocialServiceServer
    auctionHouse *social.AuctionHouse
}

// NewSocialHandler 创建社交处理器实例
func NewSocialHandler(db *data.DB) *SocialHandler {
    return &SocialHandler{
        auctionHouse: social.NewAuctionHouse(db),
    }
}

func (h *SocialHandler) ListItem(ctx context.Context, req *pb.ListItemRequest) (*pb.ListItemResponse, error) {
    itemID, err := h.auctionHouse.ListItem(req.SellerID, req.ItemID, req.Price, req.EndTime)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to list item: %v", err)
    }
    return &pb.ListItemResponse{
        Success: true,
        ItemID:  itemID,
    }, nil
}

// SendFriendRequest 发送好友请求
func (h *SocialHandler) SendFriendRequest(ctx context.Context, req *pb.FriendRequest) (*pb.FriendResponse, error) {
    log.Printf("Player %d sending friend request to %d", req.PlayerId, req.TargetId)
    
    // 检查玩家是否存在
    playerMgr := player.GetInstance()
    _, exists := playerMgr.GetPlayer(req.PlayerId)
    if !exists {
        return nil, status.Errorf(codes.NotFound, "Player not found")
    }
    
    _, targetExists := playerMgr.GetPlayer(req.TargetId)
    if !targetExists {
        return nil, status.Errorf(codes.NotFound, "Target player not found")
    }
    
    // 调用社交管理器处理好友请求
    err := social.GetInstance().SendFriendRequest(req.PlayerId, req.TargetId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to send friend request: %v", err)
    }
    
    return &pb.FriendResponse{
        Success: true,
        Message: "Friend request sent successfully",
    }, nil
}

// AcceptFriendRequest 接受好友请求
func (h *SocialHandler) AcceptFriendRequest(ctx context.Context, req *pb.AcceptFriendRequest) (*pb.FriendResponse, error) {
    log.Printf("Player %d accepting friend request from %d", req.PlayerId, req.RequesterId)
    
    // 调用社交管理器处理接受好友请求
    err := social.GetInstance().AcceptFriendRequest(req.PlayerId, req.RequesterId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to accept friend request: %v", err)
    }
    
    return &pb.FriendResponse{
        Success: true,
        Message: "Friend request accepted successfully",
    }, nil
}

// RejectFriendRequest 拒绝好友请求
func (h *SocialHandler) RejectFriendRequest(ctx context.Context, req *pb.RejectFriendRequest) (*pb.FriendResponse, error) {
    log.Printf("Player %d rejecting friend request from %d", req.PlayerId, req.RequesterId)
    
    // 调用社交管理器处理拒绝好友请求
    err := social.GetInstance().RejectFriendRequest(req.PlayerId, req.RequesterId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to reject friend request: %v", err)
    }
    
    return &pb.FriendResponse{
        Success: true,
        Message: "Friend request rejected successfully",
    }, nil
}

// DeleteFriend 删除好友
func (h *SocialHandler) DeleteFriend(ctx context.Context, req *pb.DeleteFriendRequest) (*pb.FriendResponse, error) {
    log.Printf("Player %d deleting friend %d", req.PlayerId, req.FriendId)
    
    // 调用社交管理器处理删除好友
    err := social.GetInstance().DeleteFriend(req.PlayerId, req.FriendId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to delete friend: %v", err)
    }
    
    return &pb.FriendResponse{
        Success: true,
        Message: "Friend deleted successfully",
    }, nil
}

// GetFriendList 获取好友列表
func (h *SocialHandler) GetFriendList(ctx context.Context, req *pb.GetFriendListRequest) (*pb.GetFriendListResponse, error) {
    log.Printf("Player %d requesting friend list", req.PlayerId)
    
    // 调用社交管理器获取好友列表
    friendIDs, err := social.GetInstance().GetFriendList(req.PlayerId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to get friend list: %v", err)
    }
    
    // 获取好友信息
    playerMgr := player.GetInstance()
    friends := make([]*pb.PlayerInfo, 0, len(friendIDs))
    
    for _, friendID := range friendIDs {
        friend, exists := playerMgr.GetPlayer(friendID)
        if exists {
            friends = append(friends, &pb.PlayerInfo{
                PlayerId:      friendID,
                Name:          friend.Name,
                Level:         friend.Level,
                CharacterClass: friend.Class,
                Health:        friend.Health,
                MaxHealth:     friend.MaxHealth,
                Position:      friend.Position,
                IsOnline:      friend.IsOnline,
            })
        }
    }
    
    return &pb.GetFriendListResponse{
        Success: true,
        Message: "Friend list retrieved successfully",
        Friends: friends,
    }, nil
}

// CreateGuild 创建公会
func (h *SocialHandler) CreateGuild(ctx context.Context, req *pb.CreateGuildRequest) (*pb.CreateGuildResponse, error) {
    log.Printf("Player %d creating guild: %s", req.PlayerId, req.Name)
    
    // 调用社交管理器创建公会
    guildID, err := social.GetInstance().CreateGuild(req.PlayerId, req.Name, req.Description)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to create guild: %v", err)
    }
    
    return &pb.CreateGuildResponse{
        Success:  true,
        Message:  "Guild created successfully",
        GuildId:  guildID,
    }, nil
}

// JoinGuild 加入公会
func (h *SocialHandler) JoinGuild(ctx context.Context, req *pb.JoinGuildRequest) (*pb.JoinGuildResponse, error) {
    log.Printf("Player %d joining guild %d", req.PlayerId, req.GuildId)
    
    // 调用社交管理器处理加入公会
    err := social.GetInstance().JoinGuild(req.PlayerId, req.GuildId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to join guild: %v", err)
    }
    
    return &pb.JoinGuildResponse{
        Success: true,
        Message: "Joined guild successfully",
    }, nil
}

// LeaveGuild 离开公会
func (h *SocialHandler) LeaveGuild(ctx context.Context, req *pb.LeaveGuildRequest) (*pb.LeaveGuildResponse, error) {
    log.Printf("Player %d leaving guild %d", req.PlayerId, req.GuildId)
    
    // 调用社交管理器处理离开公会
    err := social.GetInstance().LeaveGuild(req.PlayerId, req.GuildId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to leave guild: %v", err)
    }
    
    return &pb.LeaveGuildResponse{
        Success: true,
        Message: "Left guild successfully",
    }, nil
}

// GetGuildInfo 获取公会信息
func (h *SocialHandler) GetGuildInfo(ctx context.Context, req *pb.GetGuildInfoRequest) (*pb.GetGuildInfoResponse, error) {
    log.Printf("Requesting guild info for guild %d", req.GuildId)
    
    // 调用社交管理器获取公会信息
    guildInfo, err := social.GetInstance().GetGuildInfo(req.GuildId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to get guild info: %v", err)
    }
    
    return &pb.GetGuildInfoResponse{
        Success:    true,
        Message:    "Guild info retrieved successfully",
        GuildInfo:  guildInfo,
    }, nil
}    